import 'package:flutter_datetime_picker_plus/flutter_datetime_picker_plus.dart';
import 'package:jyofservice/util/webconfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jyofservice/fluro/NavigatorUtil.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:dio/dio.dart';
import 'package:jyofservice/bean/order_person_entity.dart';
import 'package:jyofservice/util/AesUtil.dart';
import 'package:jyofservice/util/CallRecordNotification.dart';

class RightEndDrawer extends StatefulWidget {
  @override
  _RightEndDrawerState createState() => _RightEndDrawerState();
}

class _RightEndDrawerState extends State<RightEndDrawer> {

  final _PhoneTextController = TextEditingController();
  final _NXTextController = TextEditingController();

  String? startTime;
  String? endTime;
  late SharedPreferences sharedPreferences;
  String? key;

  List<DropdownMenuItem> hujiaoList = [];
  List<DropdownMenuItem> kefuList = [];
  List<DropdownMenuItem> lianxianList = [];
  List<DropdownMenuItem> guaduanList = [];
  //呼叫类型
  int? hujiaoId;
  String? hujiaoName;
  late OrderPersonEntity hujiaonData;

  //客服人员
  int? kefuId;
  String? kefuName;
  late OrderPersonEntity kefuData;

  //连线情况
  int? lianxianId;
  String? lianxianName;
  late OrderPersonEntity lianxianData;

  //挂断方式
  int? guaduanId;
  String? guaduanName;
  late OrderPersonEntity guaduanData;



  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    init().then((onValue) {
      if (onValue != null) {
        //获取呼叫类型
        getHuJiaoTypeData();
        //获取客服人员
        getKeFuPersonData();
        //获取连线情况
        getLianXianTypeData();
        //获取挂断方式
        getGuaDuanTypeData();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Drawer(
      child:GestureDetector(

        behavior: HitTestBehavior.translucent,
        onTap: (){

          FocusScope.of(context).requestFocus(FocusNode());
        },

        child:  Column(
          children: <Widget>[
            AppBar(
              centerTitle: true,
              title: Text(
                '筛选',
                style: TextStyle(
                    color: Colors.white, fontSize: ScreenUtil().setSp(45)),
              ),
              actions: <Widget>[
                SizedBox(
                  width: 30,
                )
              ],
            ),
            Container(
              width: ScreenUtil().scaleWidth,
              height: ScreenUtil().setHeight(2),
              color: Colors.grey,
            ),
            Expanded(
              flex: 8,
              child: Container(
                color: Colors.white,
                padding: EdgeInsets.all(10),
                child: SingleChildScrollView(
                    child: Column(
                      children: <Widget>[

                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              '开始时间:',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil().setSp(35)),
                            ),
                            SizedBox(
                              width: ScreenUtil().setWidth(10),
                            ),
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: ScreenUtil().setHeight(80),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(Radius.circular(5)),
                                  border: Border.all(color: Colors.grey),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    TextButton(
                                      onPressed: () {
                                        DatePicker.showDateTimePicker(context,
                                            showTitleActions: true,
                                            onChanged: (date) {
                                              print('change $date');
                                            }, onConfirm: (date) {
                                              print('confirm $date');
                                              if (mounted) {
                                                setState(() {
                                                  startTime =
                                                      date.toString().substring(
                                                          0, 19);
                                                });
                                              }
                                            },
                                            currentTime: DateTime.now(),
                                            locale: LocaleType.zh);
                                      },
                                      child: Text(
                                        startTime ?? '请 选 择 开 始 时 间',
                                      ),
                                    ),
                                    Offstage(
                                      offstage: startTime==null?false:true,
                                      child:  Icon(Icons.arrow_drop_down),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: ScreenUtil().setHeight(20),
                        ),
                        Row(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: <Widget>[
                            Text(
                              '结束时间:',
                              style: TextStyle(
                                  color: Colors.black87,
                                  fontSize: ScreenUtil().setSp(35)),
                            ),
                            SizedBox(
                              width: ScreenUtil().setWidth(10),
                            ),
                            Expanded(
                              flex: 1,
                              child: Container(
                                height: ScreenUtil().setHeight(80),
                                decoration: BoxDecoration(
                                  borderRadius: BorderRadius.all(Radius.circular(5)),
                                  border: Border.all(color: Colors.grey),
                                ),
                                child: Row(
                                  children: <Widget>[
                                    TextButton(
                                      onPressed: () {
                                        DatePicker.showDateTimePicker(context,
                                            showTitleActions: true,
                                            onChanged: (date) {
                                              print('change $date');
                                            }, onConfirm: (date) {
                                              print('confirm $date');
                                              if (mounted) {
                                                setState(() {
                                                  endTime =
                                                      date.toString().substring(
                                                          0, 19);
                                                });
                                              }
                                            },
                                            currentTime: DateTime.now(),
                                            locale: LocaleType.zh);
                                      },
                                      child: Text(
                                        endTime ?? '请 选 择 结 束 时 间',
                                      ),
                                    ),
                                    Offstage(
                                      offstage: endTime==null?false:true,
                                      child:  Icon(Icons.arrow_drop_down),
                                    )
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                        SizedBox(
                          height: ScreenUtil().setHeight(10),
                        ),
                        getRow('电话号码：', '请输入电话号码', _PhoneTextController),
                        //呼叫类型
                        getHuJiaoType(),
                        getRow('内线号码：', '请输入内线号码', _NXTextController),
                        //客服人员
                        getKeFuPerson(),
                        //连线情况
                        getLianXianType(),
                        //挂断方式
                        getGuaDuanType(),
                      ],
                    )),
              ),
            ),
            Expanded(
                flex: 1,
                child: Container(

                  color: Colors.white,
                  margin:EdgeInsets.only(bottom: ScreenUtil().bottomBarHeight),
                  alignment: Alignment.bottomCenter,

                  child: Row(

                    children: <Widget>[
//                      Expanded(
//
//                        child: Container(
//                            decoration: BoxDecoration(
//                                border: Border.all(width: 1.0,color: Color(0xff4c8eff)), color: Colors.white
//                            ),
//                            height: 60.0,
//                            child:FlatButton(
//                              child: Text("重置",style: TextStyle(color:const Color(0xFF3090ff),fontSize: ScreenUtil().setSp(28) ),),
//                              onPressed:(){
//
//                                startTime = null;
//                                endTime = null;
//                                _PhoneTextController.text = "";
//                                _NXTextController.text = "";
//                                hujiaoList.clear();
//                                kefuList.clear();
//                                lianxianList.clear();
//                                guaduanList.clear();
//
//                                //呼叫类型
//                                hujiaoId=null;
//                                hujiaoName="";
//                                hujiaonData=null;
//
//                                //客服人员
//                                kefuId=null;
//                                kefuName="";
//                                kefuData=null;
//
//                                //连线情况
//                                lianxianId=null;
//                                lianxianName="";
//                                lianxianData=null;
//
//                                //挂断方式
//                                 guaduanId=null;
//                                 guaduanName="";
//                                 guaduanData=null;
//
//                                 if (mounted) {
//                    setState(() {
//
//                                 });}
//                              },
//                            )
//                        ),
//                      ),
                      Expanded(

                        child: Container(
                            decoration: BoxDecoration(

                              border: Border.all(width: 1.0,color: Color(0xff4c8eff)),
                              color: Color(0xff4c8eff),

                            ),
                            height: 60.0,
                            child:TextButton(

                              child: Text("查询",style: TextStyle(color: Colors.white,fontSize: ScreenUtil().setSp(28) ),),
                              onPressed: () {

                                _chaxun();

                              },
                            )
                        ),
                      ),

                    ],
                  ),
                )

            )
          ],
        ),
      )
    );
  }

  //电话号码和内线号码widget
  Widget getRow(
      String title, String hitText, TextEditingController controller) {
    return Container(
      padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text('$title',
              style: TextStyle(
                  color: Colors.black87, fontSize: ScreenUtil().setSp(35))),

          Expanded(
            flex: 1,
            child: Container(
              padding: EdgeInsets.only(left: 5),
              height: ScreenUtil().setHeight(80),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                border: Border.all(color: Colors.grey),
              ),
              child: TextField(

//                keyboardType: TextInputType.phone,
                decoration: InputDecoration(
                  hintText: '$hitText',
                  hintStyle: TextStyle(fontSize: ScreenUtil().setSp(28.0)),
                  border: InputBorder.none,
                ),
                controller: controller,
              ),
            ),
          )
        ],
      ),
    );
  }


  Future init() async {
    sharedPreferences = await SharedPreferences.getInstance();
    key = sharedPreferences.getString("key");
    return key;
  }

  //挂断方式widget
  Widget getGuaDuanType() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '挂断方式：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: guaduanName,
                items: guaduanList,
                hint: Text('请选择挂断方式',style: TextStyle(fontSize: ScreenUtil().setSp(28.0)),),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      guaduanName = T;
                      for (int i = 0; i < guaduanData.data!.length; i++) {
                        if (guaduanData.data![i].name == guaduanName) {
                          guaduanId = guaduanData.data![i].iD;
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //获取挂断方式数据
  Future getGuaDuanTypeData() async {
    guaduanList.clear();
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "Public_closetype",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    guaduanData = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (guaduanData.code == "200") {
      if (mounted) {
        setState(() {
          guaduanList = new List<DropdownMenuItem>.generate(
              guaduanData.data!.length,
                  (i) =>
              new DropdownMenuItem(
                  child: new Text(
                    guaduanData.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: guaduanData.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  //连线情况
  Widget getLianXianType() {

    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '连线情况：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: lianxianName,
                items: lianxianList,
                hint: Text('请选择连线情况',style: TextStyle(fontSize: ScreenUtil().setSp(28.0)),),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      lianxianName = T;

                      for (int i = 0; i < lianxianData.data!.length; i++) {
                        if (lianxianData.data![i].name == lianxianName) {
                          lianxianId = lianxianData.data![i].iD;
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);

  }

  //获取连线情况
  Future getLianXianTypeData() async {
    lianxianList.clear();
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "Public_connecttype",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    lianxianData = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (lianxianData.code == "200") {
      if (mounted) {
        setState(() {
          lianxianList = new List<DropdownMenuItem>.generate(
              lianxianData.data!.length,
                  (i) =>
              new DropdownMenuItem(
                  child: new Text(
                    lianxianData.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: lianxianData.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  //客服人员widget
  Widget getKeFuPerson() {

    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '客服人员：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: kefuName,
                items: kefuList,
                hint: Text('请选择客服人员',style: TextStyle(fontSize: ScreenUtil().setSp(28.0)),),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      kefuName = T;

                      for (int i = 0; i < kefuData.data!.length; i++) {
                        if (kefuData.data![i].name == kefuName) {
                          kefuId = kefuData.data![i].iD;
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //获取客服人员数据
  Future getKeFuPersonData() async {
    kefuList.clear();
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "vw_Sys_user",
      "wherestr": "isKeFu=1",
      "idstr": "ID",
      "namestr": "Real_name","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    kefuData = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (kefuData.code == "200") {
      if (mounted) {
        setState(() {
          kefuList = new List<DropdownMenuItem>.generate(
              kefuData.data!.length,
                  (i) =>
              new DropdownMenuItem(
                  child: new Text(
                    kefuData.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: kefuData.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  //呼叫类型widgett
  Widget getHuJiaoType() {
    return Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Text(
            '呼叫类型：',
            style: TextStyle(
                color: Colors.black87, fontSize: ScreenUtil().setSp(35)),
          ),
          SizedBox(
            width: ScreenUtil().setWidth(10),
          ),
          Expanded(
            flex: 1,
            child: SizedBox(
              width: double.infinity,
              height: ScreenUtil().setHeight(80),
              child: DropdownButton(
                isExpanded: true,
                value: hujiaoName,
                items: hujiaoList,
                hint: Text('请选择呼叫类型',style: TextStyle(fontSize: ScreenUtil().setSp(28.0)),),
                onChanged: (dynamic T) {
                  if (mounted) {
                    setState(() {
                      hujiaoName = T;

                      for (int i = 0; i < hujiaonData.data!.length; i++) {
                        if (hujiaonData.data![i].name == hujiaoName) {
                          hujiaoId = hujiaonData.data![i].iD;
                        }
                      }
                    });
                  }
                },
                style: new TextStyle(
                  //设置文本框里面文字的样式
                    color: Colors.black),
              ),
            ),
          )
        ]);
  }

  //获取呼叫类型数据
  Future getHuJiaoTypeData() async {
    hujiaoList.clear();
    String aesData= await (AesUtil.encodeBase64());
    var data = {
      "key": key,
      "view": "Public_phone_type",
      "wherestr": "1=1",
      "idstr": "ID",
      "namestr": "Name","ClientType":"phone","ClientKey":aesData
    };
    Response response = await Dio().post(
        WebConfig().baseUrl + "DB/getchoosedata",
        data: data);
    hujiaonData = OrderPersonEntity.fromJson(response.data);
    print(response.data.toString());

    if (hujiaonData.code == "200") {
      if (mounted) {
        setState(() {
          hujiaoList = new List<DropdownMenuItem>.generate(
              hujiaonData.data!.length,
                  (i) =>
              new DropdownMenuItem(
                  child: new Text(
                    hujiaonData.data![i].name ?? "",
                    style: TextStyle(
                        color: Colors.black87,
                        fontSize: ScreenUtil().setSp(35)),
                  ),
                  value: hujiaonData.data![i].name.toString() ?? ""));
        });
      }
    }
    return response.data;
  }

  void _chaxun() {

    String whereStr = "";

    if (startTime != null) {
      whereStr += " and ComeTime >= '" + (startTime ?? "") + "'";
    }

    if (endTime != null) {
      whereStr += " and ComeTime <= '" + (endTime ?? "") + "'";
    }

    if (_PhoneTextController.text.toString().length!=0) {
      whereStr += " and Phone like '%" +
          (_PhoneTextController.text.toString() ?? "") +
          "%'";
    }

    if (hujiaoId!=null) {
      whereStr += " and Type =" + (hujiaoId.toString() ?? "");
    }

    if (_NXTextController.text.toString().length!=0) {
      whereStr += " and seatnum like '%" +
          (_NXTextController.text.toString() ?? "") +
          "%'";
    }

    if (kefuId!=null) {
      whereStr += " and User_id =" + (kefuId.toString() ?? "");
    }

    if (lianxianId!=null) {
      whereStr += " and ConnectType =" + (lianxianId.toString() ?? "");
    }

    if (guaduanId!=null) {
      whereStr += " and CloseType =" + (guaduanId.toString() ?? "");
    }

    if(whereStr.length==0) {
      whereStr ="1=1";
    }else if(whereStr.startsWith(" and ")){
      whereStr = whereStr.substring(5);

    }
    print("whereStr===$whereStr");

    CallRecordNotification(wherestr: whereStr).dispatch(context);
    NavigatorUtil.goBack(context);
  }
}
